<template>
  <div class='container'>
    <el-row>
      <el-col :span='24'>
        <el-card>
          <div class="search">
            <el-row>
              <el-form class="form" label-width="100px" :model="addFormParams">
                <el-col :span="12">
                  <el-form-item label="活动名称">
                    <el-input v-model="addFormParams.title" size="mini" placeholder="请输入活动名称"></el-input>
                  </el-form-item>
                </el-col>

                <el-col :span="12">
                  <el-form-item label="开始时间">
                    <div class="block">
                      <el-date-picker
                        v-model="value1"
                        type="daterange"
                        value-format="yyyy-MM-dd"
                        format="yyyy-MM-dd"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        @change="chooseTimeRange">
                      </el-date-picker>
                    </div>
                  </el-form-item>
                </el-col>

                <el-col :span="8" :offset="8">
                  <el-form-item></el-form-item>
                  <el-form-item>
                    <el-button @click="submitSearch()">搜索</el-button>
                    <el-button @click="clearListSearch">重置</el-button>
                  </el-form-item>
                </el-col>
              </el-form>
            </el-row>
          </div>

          <div slot="header">
            <bread></bread>
          </div>

          <div class="business-table">
            <div class="table-wrapper">
              <el-table
                :data="userList"
                style="width: 100%"
                align='center'
                :header-cell-style="{background:'#eef1f6'}"
              >
                <el-table-column
                  label="序号"
                  align='center'
                  width="50"
                >
                  <template slot-scope='scope'>
                    <span>{{scope.$index + 1}}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="sort"
                  label="排序"
                  align='center'
                  width="50"
                >
                </el-table-column>
                <el-table-column
                  prop="createTime"
                  label="创建时间"
                  align='center'
                  width="100"
                >
                </el-table-column>
                <el-table-column
                  prop="title"
                  label="活动名称"
                  align='center'
                  width="150"
                >
                </el-table-column>
                <el-table-column
                  prop="intro"
                  label="活动简介"
                  align='center'
                  :show-overflow-tooltip="true"
                >
                </el-table-column>
                <el-table-column
                  prop="startTime"
                  label="开始时间"
                  width="100"
                  align='center'>
                </el-table-column>
                <el-table-column
                  prop="endTime"
                  label="结束时间"
                  align='center'>
                </el-table-column>
                <el-table-column
                  label="是否开启"
                  align='center'>
                  <template slot-scope='scope'>
                    <el-switch v-model="scope.row.isOpen"
                               :active-value="1"
                               :inactive-value="0"
                               @change="changeSwitch(scope.row)"
                    >
                    </el-switch>
                  </template>
                </el-table-column>
                <el-table-column
                  align='center'
                  label="操作"
                  width="180">
                  <template slot-scope='scope'>
                    <el-col>
                      <el-col>
                        <el-button v-if="scope.row.isOpen === 0" @click="showDialog(2, scope.row)" type="text"
                                   size="mini">
                          编辑
                        </el-button>
                        <el-button v-if="scope.row.isOpen === 0" @click="showDialog(3, scope.row)" type="text"
                                   size="mini">
                          删除
                        </el-button>
                      </el-col>
                      <el-col>
                        <el-button @click="activityGoods(1,scope.row)" type="text" size="mini">
                          查看活动商品
                        </el-button>
                      </el-col>
                      <el-col>
                        <el-button @click="activityGoods(2,scope.row)" type="text" size="mini">
                          编辑活动商品
                        </el-button>
                      </el-col>
                    </el-col>

                  </template>
                </el-table-column>
              </el-table>
              <div class="table-footer">
                <el-row>
                  <el-col>
                    <el-button @click="showDialog(1)" size="small">
                      添加
                    </el-button>
                  </el-col>
                </el-row>
              </div>
            </div>

          </div>
          <div class="pagination">
            <pagination :pageTotal="pageTotal" @handleCurrentChange="handleCurrentChange"
                        @handleSizeChange="handleSizeChange"></pagination>
          </div>
        </el-card>

        <!-- 删除提示框 -->
        <el-dialog title="提示" :visible.sync="delVisible" width="300px" center :modal-append-to-body="false">
          <div class="del-dialog-cnt">删除不可恢复，是否确定删除？</div>
          <div slot="footer" class="dialog-footer">
            <el-button @click="delVisible = false">取 消</el-button>
            <el-button type="primary" @click="deleteRow()">确 定</el-button>
          </div>
        </el-dialog>

        <!-- 活动编辑添加提示框 -->
        <el-dialog :visible.sync="activityVisible" width="50%" center :modal-append-to-body="false">
          <div>
            <el-form :model="addFormParams" label-width="120px">
              <el-row>
                <el-col>
                  <div class="dialog-title">
                    <span v-if="dialogNum == 1">添加活动</span>
                    <span v-if="dialogNum == 2">修改活动</span>
                  </div>
                </el-col>
                <el-col>

                  <el-form-item label="活动展示位置:">
                    <el-select v-model="addFormParams.type" placeholder="请选择" style="width:100%">
                      <el-option
                        v-for="item in positionList"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                        <span style="float: left">{{ item.label }}</span>
                      </el-option>
                    </el-select>
                  </el-form-item>

                  <el-form-item label="排序:">
                    <el-input v-model="addFormParams.sort" size="mini" placeholder="请输入排序"></el-input>
                  </el-form-item>

                  <el-form-item label="活动名称:">
                    <el-input v-model="addFormParams.title" size="mini" placeholder="请输入名称"></el-input>
                  </el-form-item>

                  <el-form-item label="活动简介:">
                    <el-input v-model="addFormParams.intro" size="mini" placeholder="请输入内容"></el-input>
                  </el-form-item>

                  <el-form-item label="活动图片">
                    <el-upload
                      class="avatar-uploader"
                      action="http://www.ccppvip.com:8081/upload"
                      :show-file-list="false"
                      :on-success="handleAvatarSuccess">
                      <img v-if="addFormParams.img" :src="addFormParams.img" class="avatar" width="40%">
                      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                  </el-form-item>

                  <el-form-item label="是否开启:">
                    <el-switch v-model="addFormParams.isOpen"
                               active-value="1"
                               inactive-value="0"
                               @change="addSwitch()"
                    >
                    </el-switch>
                  </el-form-item>

                </el-col>
                <el-col>
                  <el-form-item>
                    <el-button @click="closeDialog">取消</el-button>
                    <el-button v-if="num == 1" type="primary" @click="addActivity">确定</el-button>
                    <el-button v-if="num == 2" type="primary" @click="changeActivity">确定</el-button>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </el-dialog>

        <!-- 查看编辑活动商品提示框 -->
        <el-dialog :visible.sync="seeGoodsVisible" width="50%" center :modal-append-to-body="false">
          <div class="business-table">
            <el-form class="form" label-width="100px" :model="activityParams" v-if="activityGoodsNum">
              <el-col :span="16">
                <el-form-item label="所属区域">
                  <el-cascader ref="address" size="large" :options="optionProps" v-model="selectedOptions" @change="handleChange">
                  </el-cascader>
                </el-form-item>

              </el-col>
              <el-col :span="4">
                <el-form-item>
                  <el-button @click="submitSearch()">搜索</el-button>
                </el-form-item>
              </el-col>
            </el-form>
            <div class="table-wrapper">
              <el-table
                :data="activityGoodsList"
                style="width: 100%"
                align='center'
                :header-cell-style="{background:'#eef1f6'}"
                @selection-change="handleGoodsChange"
              >
                <el-table-column
                  v-if="activityGoodsNum"
                  type="selection"
                  align='center'
                  width="50">
                </el-table-column>
                <el-table-column
                  label="序号"
                  align='center'
                >
                  <template slot-scope='scope'>
                    <span>{{scope.$index + 1}}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="title"
                  label="商品名称"
                  align='center'
                  width="200"
                  :show-overflow-tooltip="true"
                >
                </el-table-column>
                <el-table-column
                  prop="id"
                  label="商品编号"
                  align='center'
                >
                </el-table-column>
                <el-table-column
                  prop="startTime"
                  label="创建时间"
                  align='center'
                >
                </el-table-column>
              </el-table>
              <div class="table-footer" v-if="activityGoodsNum">
                <el-row>
                  <el-col>
                    <el-button @click="onAddGoods()" size="small">
                      添加
                    </el-button>
                  </el-col>
                </el-row>
              </div>
            </div>
          </div>
          <div class="pagination">
            <pagination :pageTotal="goodPageTotal" @handleCurrentChange="goodsPageChange"
                        @handleSizeChange="goodsSizeChange"></pagination>
          </div>
        </el-dialog>

      </el-col>
    </el-row>
  </div>
</template>
<script>
import pagination from '../../common/pagination'
import bread from '../../common/bread'
import {
  activityList,
  addActivity,
  changeActivity,
  delActivity,
  seeGoods,
  changeGoods,
  goodsVisible,
  isOpen, queryAddress
} from '../../api/api'
import { MessageBox } from 'element-ui'

export default {
  data () {
    return {
      optionProps: {
        value: 'id',
        label: 'name',
        children: 'child'
      },
      userList: [],
      pageTotal: 0,
      goodPageTotal: 0,
      value1: '',
      selectedOptions: [],
      activityVisible: false,
      delVisible: false,
      addFormParams: {
        pageNum: 1,
        pageSize: 10,
        userId: sessionStorage.getItem('userId'),
        startTime: '',
        endTime: '',
        id: '',
        title: '',
        sort: '',
        img: '',
        type: '',
        intro: '',
        isOpen: ''
      },
      delFormParams: {
        id: ''
      },
      dialogNum: 1,
      positionList: [{
        value: '0',
        label: '首页'
      }, {
        value: '1',
        label: '找好物'
      }],
      num: '',
      seeGoodsVisible: false,
      activityGoodsList: [],
      activityParams: {
        pageNum: 1,
        pageSize: 10,
        province: '',
        city: '',
        county: ''
      },
      activityGoodsNum: false,
      multipleSelection: [],
      productIds: []
    }
  },
  mounted () {
    this.getGoodsList()
  },
  methods: {
    handleAvatarSuccess (res, file) {
      this.addFormParams.img = URL.createObjectURL(file.raw)
      this.addFormParams.img = JSON.parse(res.slice(5)).data.split('?')[0]
      console.log(this.addFormParams.img)
    },
    chooseTimeRange (value) {
      for (var x in value) {
        this.addFormParams.startTime = value[0]
        this.addFormParams.endTime = value[1]
      }
    },
    // 格式化表单数据
    clearForm () {
      this.addFormParams = {
        pageNum: 1,
        pageSize: 10,
        userId: sessionStorage.getItem('userId'),
        startTime: '',
        endTime: '',
        province: '',
        city: '',
        county: '',
        id: '',
        title: '',
        sort: '',
        img: '',
        type: '',
        intro: '',
        isOpen: ''
      }
    },
    // 清除列表的搜索表单
    clearListSearch () {
      this.clearForm()
      this.value1 = ''
      this.getGoodsList()
    },
    show (scope) {
      console.log(scope)
    },

    handleClick () {
      this.clearForm()
      this.getGoodsList()
    },

    // 表格数据
    getGoodsList (type) {
      this.userList = []
      const para = Object.assign({}, this.addFormParams)
      activityList(para).then(res => {
        console.log(res)
        this.userList = res.data.list
        this.pageTotal = res.data.total
      })
    },
    // 上下分页
    handleCurrentChange (val) {
      this.addFormParams.pageNum = val
      this.getGoodsList()
    },
    // 每页显示多少条
    handleSizeChange (val) {
      this.addFormParams.pageSize = val
      this.getGoodsList()
    },
    submitSearch () {
      this.getGoodsList()
    },
    getDate (date) {
      console.log(date)
    },
    queryAddress() {
      queryAddress().then(res => {
        this.optionProps = res.data;
      })
    },
    handleChange (value) {
      let labels = this.$refs['address'].getCheckedNodes()[0].pathLabels;
      this.addFormParams.province = labels[0];
      this.addFormParams.city = labels[1] === '全部' ? '' : labels[1];
      this.addFormParams.county = labels[2] === '全部' ? '' : labels[2];
    },
    showDialog (num, row) {
      this.num = num
      if (num === 2) {
        console.log(row)

        this.activityVisible = true
        this.addFormParams.id = row.id
        this.addFormParams.title = row.title
        this.addFormParams.sort = row.sort
        this.addFormParams.img = row.img
        this.addFormParams.type = row.type
        this.addFormParams.intro = row.intro
        this.addFormParams.isOpen = row.isOpen
      } else if (num === 1) {
        this.activityVisible = true
        this.clearForm()
      } else {
        this.delFormParams.id = row.id
        this.delVisible = true
      }
      this.dialogNum = num
    },
    addActivity () {
      const para = Object.assign({}, this.addFormParams)
      addActivity(para).then(res => {
        if (res.code === 0) {
          this.closeDialog()
          this.clearForm()
          this.getGoodsList()
          this.$toast('添加成功')
        } else {
          this.$toast(res.msg)
        }
      })
    },
    changeActivity () {
      const para = Object.assign({}, this.addFormParams)
      changeActivity(para).then(res => {
        if (res.code === 0) {
          this.closeDialog()
          this.clearForm()
          this.getGoodsList()
          this.$toast('修改成功')
        } else {
          this.$toast(res.msg)
        }
      })
    },
    deleteRow () {
      const para = Object.assign({}, this.delFormParams)
      delActivity(para).then(res => {
        if (res.code === 0) {
          this.closeDialog()
          this.clearForm()
          this.getGoodsList()
          this.$toast('修改成功')
        } else {
          this.$toast(res.msg)
        }
      })
    },
    closeDialog () {
      this.activityVisible = false
      this.delVisible = false
    },
    changeSwitch (row) {
      this.addFormParams.id = row.id
      this.addFormParams.isOpen = row.isOpen
      const para = Object.assign({}, this.addFormParams)
      isOpen(para).then(res => {
        if (res.code === 0) {
          this.closeDialog()
          this.getGoodsList()
          this.$toast('修改成功')
        } else {
          this.$toast(res.msg)
        }
      })
    },
    addSwitch () {
      console.log(this.addFormParams.isOpen)
    },
    activityGoods (num, row) {
      console.log(row)
      this.seeGoodsVisible = true
      this.addFormParams.id = row.id
      this.addFormParams.isOpen = row.isOpen
      if (num === 1) {
        this.activityGoodsNum = false
        this.seeGoods()
      } else {
        this.activityGoodsNum = true
        this.addGoods()
      }
    },
    seeGoods () {
      const para = Object.assign({}, this.addFormParams)
      seeGoods(para).then(res => {
        console.log(res)
        this.activityGoodsList = res.data.list
        this.goodPageTotal = res.data.total
      })
    },
    addGoods () {
      const para = Object.assign({}, this.addFormParams)
      changeGoods(para).then(res => {
        console.log(res)
        this.activityGoodsList = res.data.list
        this.goodPageTotal = res.data.total
      })
    },
    goodsPageChange (val) {
      this.activityParams.pageNum = val
      this.seeGoods()
    },
    // 每页显示多少条
    goodsSizeChange (val) {
      this.activityParams.pageSize = val
      this.seeGoods()
    },
    changeGoods (row) {
      this.addFormParams.id = row.id
      this.changeActivity()
    },
    handleGoodsChange (val) {
      this.multipleSelection = val
      console.log(this.multipleSelection)
    },
    onAddGoods () {
      const length = this.multipleSelection.length
      // 转换shopIDS 数组为字符串
      this.productIds = []
      for (let i = 0; i < length; i++) {
        this.productIds.push(this.multipleSelection[i].productId)
      }
      this.productIds = this.productIds.join(',')
      console.log(this.productIds)
      if (this.multipleSelection.length === 0) {
        MessageBox.alert('至少选择一项', '提示', {
          confirmButtonText: '确定',
          showClose: false,
          type: 'error'
        })
        this.seeGoodsVisible = false
      } else {
        const para = Object.assign({}, {
          productIds: this.productIds,
          id: this.addFormParams.id,
          isOpen: this.addFormParams.isOpen
        })
        console.log(para)
        goodsVisible(para).then(res => {
          console.log(res)
          this.$toast(res.msg)
          this.seeGoodsVisible = false
        })
      }
    }
  },
  components: {
    pagination,
    bread
  }
}
</script>
<style lang='scss'>
  .business-tabs {
    margin: 0 0 10px 0;
  }

  .el-dialog--small {
    width: 600px !important;
  }

  .container {
    .search {
      margin: 0 0 20px 0;
    }

    .el-table {
      .warning-row {
        background-color: oldlace;
      }
    }

    .recommend-tag {
      display: inline-block;
      margin: 4px 0;
      margin-right: 4px;

      &:last-child {
        margin-right: 0;
      }
    }

    .table-footer {
      padding: 10px;
      background: #eef1f6;
    }

    .dialog-title {
      margin: 0 0 30px;
      text-align: center;
      font-size: 20px;
    }
  }
</style>
